package com.xwaiy.xwaiyrpc.spi;

import cn.hutool.core.io.resource.ResourceUtil;
import com.xwaiy.xwaiyrpc.exception.RpcException;
import com.xwaiy.xwaiyrpc.exception.enums.ErrorCode;
import com.xwaiy.xwaiyrpc.serializer.Serializer;
import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * SPI加载器
 * @Author Xwaiy
 * @Date 2025/8/25 16:41
 **/
@Slf4j
public class SpiLoader {
    /**
     * 存已加载的
     * 接口名称：(key:实现类)
     */
    private static Map<String, Map<String,Class<?>>> loaderMap = new ConcurrentHashMap<>();

    /**
     * 缓存
     */
    private static Map<String,Object> instanceCache = new ConcurrentHashMap<>();

    // 系统spi目录
    private static final String RPC_SYSTEM_SPI = "META-INF/rpc/system";

    // 自定义spi目录
    private static final String RPC_CUSTOM_SPI = "META-INF/rpc/custom";

    // 扫描路径
    private static final String[] SCAN_DIRS = new String[]{RPC_SYSTEM_SPI, RPC_CUSTOM_SPI};

    // 动态加载的类列表
    private static final List<Class<?>> LOAD_CLASS_LIST = Arrays.asList(Serializer.class);

    // 加载所有类型
    public static void loadAll(){
        log.info("加载全部...");
        for(Class<?> clazz : LOAD_CLASS_LIST){
            load(clazz);
        }
    }

    // 获取实例
    public static <T> T getInstance(Class<?> clazz,String key){
        String className = clazz.getName();
        Map<String,Class<?>> map = loaderMap.get(className);
        if(map == null){
            throw new RpcException(ErrorCode.SYSTEM_ERROR, "SpiLoader未加载"+className);
        }
        if(!map.containsKey(key)){
            throw new RpcException(ErrorCode.SYSTEM_ERROR, "SpiLoader的"+className+"不存在"+key);
        }
        Class<?> implClass = map.get(key);
        String implClassName = implClass.getName();
        if (!instanceCache.containsKey(implClassName)) {
            try{
                instanceCache.put(implClassName,implClass.newInstance());
            }catch (InstantiationException | IllegalAccessException e){
                throw new RpcException(ErrorCode.SYSTEM_ERROR, implClassName+"类实例化失败",e);
            }
        }
        return (T)instanceCache.get(implClassName);
    }

    public static Map<String,Class<?>> load(Class<?> clazz){
        log.info("加载类型为{}的spi...",clazz.getName());
        Map<String,Class<?>> map = new HashMap<>();
        for (String scan : SCAN_DIRS) {
            List<URL> resources = ResourceUtil.getResources(scan+clazz.getName());
            for(URL resource : resources){
                try{
                    InputStreamReader input = new InputStreamReader(resource.openStream());
                    BufferedReader bufferedReader = new BufferedReader(input);
                    String line;
                    while ((line=bufferedReader.readLine()) != null) {
                        String[] split = line.split("=");
                        if(split.length>1){
                            String key = split[0];
                            String className = split[1];
                            map.put(key,Class.forName(className));
                        }
                    }
                }catch (Exception e){
                    log.error("spi加载失败",e);
                }
            }
        }
        loaderMap.put(clazz.getName(),map);
        return map;
    }
}
